var fs = require("fs")
var path = require('path');

// Eduic API Key（需要替换为你的实际 API Key）
const EDUIC_API_KEY = "NIS Sm+T1/9gRLRjfHiRvbxgRv+1ezMgisDaEfYHjBnHOxNiRhWQoK3gHQ=="; // 替换为你的 Eduic API Key
const EDUIC_API_ALL_WORDBOOK_URL = "https://api.frdic.com/api/open/v1/studylist/category?language=en"; // 假设这是获取单词本的 API URL
const EDUIC_API_ALL_WORD_URL = "https://api.frdic.com/api/open/v1/studylist/words"
var fs = require("fs")


// 异步函数：获取个人单词本
async function fetchPersonalWordbook(URL, requestBody = {}, method = "GET") {
    try {
        // 设置请求头，包含 API Key 和内容类型
        const headers = {
            "Authorization": `${EDUIC_API_KEY}`, // Bearer Token 认证方式
            "Content-Type": "application/json", // JSON 数据格式
            ...requestBody,
        };
        // console.log(URL, requestBody, headers, `响应输出`)

        // 发送 GET 请求到 Eduic API
        const response = await fetch(URL, { method, headers });
        console.log(response, `响应输出`)
        // 检查响应是否成功（状态码为 200-299）
        if (response.ok) {
            const wordbookData = await response.json(); // 解析 JSON 数据
            return wordbookData; // 返回单词本数据对象
        } else {
            // 打印错误状态码和消息到控制台中显示失败原因及状态码等信息以便于调试和修复问题。例如：401 Unauthorized,404 Not Found等等常见错误状态码及其对应含义如下表所示：400 Bad Request,401 Unauthorized,403 Forbidden,500 Internal Server Error等等常见错误状态码及其对应含义如下表所示：400 Bad Request,401 Unauthorized,403 Forbidden,500 Internal Server Error等等常见错误状态码及其对应含义如下表所示：400 Bad Request,401 Unauthorized
            console.error("请求失败，状态码:", response.status);
        }
    } catch (err) {

    }
}

async function main() {
    let rqBody = { method: "POST" }
    let workBooks = await fetchPersonalWordbook(EDUIC_API_ALL_WORDBOOK_URL)
    if (!workBooks) return;
    console.log("个人单词本数据:", workBooks); // 打印单词本数据到控制台
    console.log(workBooks.data, `打印输出`)
    var RequestWord = EDUIC_API_ALL_WORD_URL + "/" + workBooks.data[7]?.id + "?language=en&page_size=20000";
    let works = await fetchPersonalWordbook(RequestWord, {})
    console.log("个人单词数据:", works); // 打印单词本数据到控制台
    if (works && works.data) {
        let spellString = ""
        works.data.forEach(element => {
            // works.note.forEach(element => {
            // spellString = spellString + element.word + "\r\n" + element.note + "\r\n\n"
            spellString = spellString + element.word + "\r\n"
        });
        // console.log(spellString, `打印输出`)
        fs.writeFile(path.join(__dirname, './欧路api_单词.txt'), spellString, function (err) {
            if (err) { return console.error(err) }

            fs.readFile(path.join(__dirname, './欧路api_单词.txt'), function (err, data) {
                if (err) { return console.error(err) }
                // console.log("异步读取文件数据: " + data.toString())
                console.log("异步读取文件数据: " + "数据完成")
            })
        })
    }
}
main()
